package com.meichis.mcsappframework.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by pei on 2016/12/13.
 */

public class BitmapUtil {
    /**
     * 添加水印
     */
    public static Bitmap addWatermark(Bitmap bitmap, String watermark) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Bitmap newBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        Canvas mCanvas = new Canvas(newBitmap);
        mCanvas.drawBitmap(bitmap, 0, 0, null);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.YELLOW);
        textPaint.setTextSize((w > h ? w : h) / 40);
        StaticLayout layout = new StaticLayout(watermark, textPaint, w, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
        mCanvas.translate(0, h - layout.getHeight());
        layout.draw(mCanvas);
        mCanvas.save();
        mCanvas.restore();
        return newBitmap;
    }

    /**
     * Bitmap保存本地
     *
     * @param bitmap
     * @param quality
     * @param dirPath
     * @param name
     * @return
     * @throws IOException
     */
    public static File Bitmap2File(Bitmap bitmap, int quality, String dirPath, String name) throws IOException {
        File fileFolder = new File(dirPath);
        if (!fileFolder.exists()) { // 如果目录不存在，则创建一个
            fileFolder.mkdirs();
        }
        File jpgFile = new File(fileFolder, name + ".jpg");
        FileOutputStream out = new FileOutputStream(jpgFile);
        if (!bitmap.compress(Bitmap.CompressFormat.JPEG, quality, out))
            jpgFile = null;
        out.flush();
        out.close();
        return jpgFile;
    }
}
